<template>
    <div v-if="status === 0" style="background-position: center;background-size: cover;width: 100%;height:100%" :style="{
        backgroundImage: `url(${bing.data})`
    }">
        <div @click="() => {

        }"
            style="width: 100%;height: 60px;display: flex;justify-content: center;align-items: flex-end;font-size: 16px;color: white;padding-bottom: 12px;backdrop-filter: blur(20px);background-color: rgba(255,255,255,0.6);">

        </div>
        <div style="width: 100%;height: calc(100% - 60px);overflow-y: auto;background-color: #fff;">
            <div style="width: 100%;background-color: rgb(242,242,242);padding: 16px;margin-top: 8px;">
                <input v-model="login.form.account" placeholder="账号" type="text"
                    style="border: 0;border-bottom: 1px solid gray;background-color: transparent;height: 32px;font-size: 16px;width: 100%;">
            </div>
            <div style="width: 100%;background-color: rgb(242,242,242);padding: 16px;margin-top: 8px;">
                <input v-model="login.form.password" placeholder="密码" type="password"
                    style="border: 0;border-bottom: 1px solid gray;background-color: transparent;height: 32px;font-size: 16px;width: 100%;">
            </div>
            <div style="width: 100%;padding: 16px;">
                <cButton @click="login.handle()" style="width: 100%;height: 48px;">登录</cButton>
            </div>
        </div>
    </div>
    <div v-if="status === 1" style="background-position: center;background-size: cover;width: 100%;height:100%" :style="{
        backgroundImage: `url(${bing.data})`
    }">
        <FlexBox style="width: 100%;height: 100%;position: fixed;left: 0;top: 0;">

            <FlexBox flex-direction="column" gap="16px"
                style="width: 400px;height: auto;box-shadow: 0 4px 10px rgba(0,0,0,0.2);border-radius: px;position: relative;overflow: hidden;padding: 16px;"
                justify-content="flex-start">
                <span style="font-size: 22px;font-weight: bold;text-align: left;width: 100%;">欢迎使用</span>
                <input @keypress="(e) => {
                    if (e.code == 'Enter') {
                        tool.focusElementById('login_password')
                    }
                }" id="login_account" v-model="login.form.account" placeholder="账号" type="text">
                <input @keypress="(e) => {
                    if (e.code == 'Enter') {
                        login.handle()
                    }
                }" id="login_password" v-model="login.form.password" placeholder="密码" type="password">
                <div style="width: 100%;text-align: right;">
                    <cButton style="width: 80px;height: 32px;">登录</cButton>
                </div>
            </FlexBox>

        </FlexBox>
    </div>
</template>

<script setup>
import { ref, reactive, defineProps, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import tool from '../tool'
import controls from '../controls/controls';
import cButton from '../components/button.vue'
import sha256 from 'js-sha256'
import FlexBox from '../components/flexBox.vue';
import axios from 'axios';

const status = ref(0)

const login = reactive({
    form: {
        account: '',
        password: ''
    },
    async handleAutoLogin() {
        let userLoginData = tool.localStorage.getItem('userLoginData')
        if (userLoginData !== null) {
            this.form = userLoginData
            await this.handle(true)
        }
    },
    async handle(isAuto = false) {
        if (!this.form.account) {
            controls.toast.show({
                content: '输入账号',
                icon: 'error'
            })
            return
        }
        if (!this.form.password) {
            controls.toast.show({
                content: '输入密码',
                icon: 'error'
            })
            return
        }
        let re = await tool.requestData('/user/login', tool.Object.assign(this.form, {
            password: sha256(this.form.password)
        }))
        if (re.status) {
            if (!isAuto) {
                controls.toast.show({
                    content: '登录成功',
                    icon: 'success',
                    mask: true
                })
                await tool.wait(0.5)
                tool.store.setItem('userData', re.data)
                tool.router.push('/')
                if (tool.localStorage.getItem('userLoginData') === null) {
                    let modal_savePassword = controls.modal({
                        title: '提示',
                        content: '是否保存登录信息，下次打开网站时自动登录？',
                        showCancel: true,
                        okCallBack: () => {
                            tool.localStorage.setItem('userLoginData', this.form)
                            modal_savePassword.close()
                        }
                    })
                }
            } else {
                tool.store.setItem('userData', re.data)
                tool.router.push('/')
            }
        } else {
            tool.localStorage.removeItem('userLoginData')
            controls.toast.show({
                content: re.content,
                icon: 'error'
            })
        }
    }
})

const bing = reactive({
    async get() {
        try {
            const response = await axios.get('https://dailybing.com/api/v1/today/ja-jp/FHD', { responseType: 'arraybuffer' })
            const base64Image = btoa(
                new Uint8Array(response.data)
                    .reduce((data, byte) => data + String.fromCharCode(byte), '')
            )
            this.data = `data:image/jpeg;base64,${base64Image}`
        } catch (error) {
            console.error('Error fetching image:', error)
            this.data = ''
        }
    },
    data: ''
})

onMounted(async () => {
    tool.store.onChangeAndNotify('windowStatus', (e) => {
        status.value = e
    })
    login.handleAutoLogin()
    setTimeout(() => {
        tool.focusElementById('login_account')
    }, 100);


})

</script>

<style scoped></style>